<!-- 事件日志 -->
<template>
  <!-- <div class="dashboard-editor-container"> -->
    <el-row style="background: #fff;">
      <connsearch ref="connsearch" :formOptions="formOptions" @search="search" @reset="reset">
    
      </connsearch>
      <div class="tabclick">
        <div class="tabitem" @click="handleClick()">
          <span><i :class="tab ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i></span>
        </div>
      </div>
      <el-row>
        <el-tabs type="border-card" v-if="tab" style="margin-top:16px;"  @tab-click="tabClick">
          <!-- <el-tab-pane label="按日统计趋势" lazy>
            <el-col :xs="24" :sm="24" :lg="24">
              <barchart :chartData="barchartData" @barclick="echartsClick" title="按日统计趋势"/>
            </el-col>
          </el-tab-pane> -->
          <!-- <el-tab-pane label="按分区统计分析" lazy>
            <el-row :gutter="20">
              <el-col :xs="24" :sm="24" :lg="24">
                <piechart  :chartData="pie1Data" @pieclick="echartsClick" title="按分区统计分析"/>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="按校区统计分析" lazy>
            <el-col :xs="24" :sm="24" :lg="24">
              <piechart :chartData="pie2Data" @pieclick="echartsClick" title="按校区统计分析"/>
            </el-col>
          </el-tab-pane> -->
          <el-tab-pane label="按资产统计分析" lazy>
            <el-col :xs="24" :sm="24" :lg="24">
              <piechart :chartData="pie3Data" @pieclick="echartsClick" title="按资产统计分析"/>
            </el-col>
          </el-tab-pane>
          <el-tab-pane label="按软件分类统计分析" lazy>
            <el-col :xs="24" :sm="24" :lg="24">
              <piechart :chartData="pie4Data" @pieclick="echartsClick" title="按软件分类统计分析"/>
            </el-col>
          </el-tab-pane>
          <el-tab-pane label="按软件名称统计分析" lazy>
            <el-col :xs="24" :sm="24" :lg="24">
              <piechart :chartData="pie5Data" @pieclick="echartsClick" title="按软件名称统计分析"/>
            </el-col>
          </el-tab-pane>
        </el-tabs>
      </el-row>
      <el-col :xs="{ span: 24 }" :sm="{ span: 24 }" :md="{ span: 24 }" :lg="{ span: 24 }" :xl="{ span: 24 }" style="padding-right: 8px;margin:16px 0;">
        <el-table stripe border :data="tableData" style="width: 100%; margin-top: 15px">
          <el-table-column label="序号"  width="60" type="index" :index='(index)=>{return (index + 1) + (this.pageNum - 1)*this.pageSize}'> </el-table-column>
          <!-- <el-table-column label="所在分区" show-overflow-tooltip prop="PrimArea" width="150" align="left">
              <template slot-scope="{row}">
                <span>{{ row.PrimArea }} / {{ row.SecondArea }}</span>
              </template>
            </el-table-column>
          <el-table-column label="所在校区" show-overflow-tooltip prop="SchoolName" align="left"></el-table-column> -->
          <el-table-column label="资产名称" show-overflow-tooltip prop="DeviceName" align="left"></el-table-column>
          <el-table-column label="采集时间" show-overflow-tooltip prop="TransTime" align="left"></el-table-column>
          <el-table-column label="软件分类" show-overflow-tooltip prop="AppClass" align="left">
            <template slot-scope="{row}">
              <span>{{ row.AppClass === '' ? '未知分类' : row.AppClass }}</span>
            </template>
          </el-table-column>
          <el-table-column label="软件名称" show-overflow-tooltip prop="AppName" align="left"></el-table-column>
          <el-table-column label="操作系统" show-overflow-tooltip prop="OSClass" align="left"></el-table-column>
          <!-- <el-table-column label="发布产商" show-overflow-tooltip prop="Descp" align="left"></el-table-column>
          <el-table-column label="版本号 "  show-overflow-tooltip prop="Version" align="left"></el-table-column> -->
          <!-- <el-table-column label="操作" width="120px" align="left" fixed="right" >
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="changeModer(scope.row)">加入字典</el-button>
            </template>
          </el-table-column> -->
        </el-table>
        <el-pagination 
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" 
          :current-page=pageNum
          :page-size=pageSize
          background 
          layout="total, prev, pager, sizes, next, jumper"
          :total="total">
        </el-pagination>
      </el-col>
      <el-dialog 
        :close-on-click-modal="false" 
        :close-on-press-escape="false" 
        :visible.sync="moderVisible"
        title="加入字典" 
        v-el-drag-dialog @close="Moder = {}" width="30%">
        <el-form label-width="100px" :rules="rules" :model="Moder" ref="Moder">
          <el-form-item label="软件名称" prop="Descp">
            <el-input placeholder="请输入软件名称" maxlength="64" disabled v-model="Moder.Descp"></el-input>
          </el-form-item>
          <el-form-item label="软件分类" prop="Class">
            <el-select v-model="Moder.Class" placeholder="请选择软件分类" style="width:100%">
              <el-option  v-for="(item, index) in dictionaryList" :key="index" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="软件版本" prop="Version">
            <el-input placeholder="请输入软件版本" maxlength="32" v-model="Moder.Version"></el-input>
          </el-form-item>
          <el-form-item label="操作系统" prop="OSClass">
            <el-select v-model="Moder.OSClass" style="width:100%" placeholder="请选择适用系统">
              <el-option  label="Windows" value="Windows"></el-option>
              <el-option  label="Mac" value="Mac"></el-option>
              <el-option  label="Android" value="Android"></el-option>
              <el-option  label="Linux" value="Linux"></el-option>
              <el-option  label="Other" value="Other"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="系统类型" prop="OSType">
            <el-select v-model="Moder.OSType" style="width:100%" placeholder="请选择系统类型">
              <el-option label="全部" value=""></el-option>
              <el-option label="64" value="64"></el-option>
              <el-option label="32" value="32"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="软件类型" prop="Property">
            <el-select v-model="Moder.Property" style="width:100%" placeholder="请选择软件类型">
              <el-option label="必装软件" :value="1"></el-option>
              <el-option label="非法软件" :value="2"></el-option>
              <el-option label="选装软件" :value="3"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submit()">确 定</el-button>
          <el-button type="info" @click="moderVisible = false">取 消</el-button>
        </span>
      </el-dialog>
    </el-row>
  <!-- </div> -->
</template>

<script>
import Cookies from 'js-cookie'
import connsearch from "@/components/connSearch";
import barchart from "./components/barchart.vue";
import piechart from "./components/piechart.vue";
import { getNowDay, parseTime, formatTime2 } from "@/utils/index.js";
import { connrequest } from "@/api/firstPage.js"
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
export default {
  directives: { elDragDialog },
  components: { connsearch, barchart, piechart },
  data() {
    let that = this
    return {
      activeName: "",
      tabTitle: '按资产统计分析',
      pageNum: 1,
      pageSize: 10,
      total: 0,
      tab: false,
      barchartData: {xAxis:[],series:[]},
      moderVisible: false,
      Moder: {},
      partitionList:[],
      dictionaryList: [],
      rules: {},
      pie1Data: [],
      pie2Data: [],
      pie3Data: [],
      pie4Data: [],
      pie5Data: [],
      tableData:[],
      searchform:{},
      options:{},
      searchobj: {},
      formOptions: [
        // {
        //   col: 8,
        //   hidden: false,
        //   label: "日期", // label文字
        //   prop: "timeRange", // 字段名
        //   initValue: [], // 字段初始值,
        //   element: "el-date-picker", // 指定elementui组件
        //   type: "", // 日期选择类型,
        //   events: {
        //     input(val) {
        //       that.searchform.timeRange = val
        //     },
        //   },
        // },
        // {
        //   col: 8,
        //   label: "分区校区选择",
        //   prop:"SchoolName",
        //   element: "el-cascader",
        //   initValue: "",
        //   placeholder: "请选择校区",
        //   options:[],
        //   props:{emitPath: true, checkStrictly: true, lazy: true, lazyLoad: that.lazyLoad},
        //   events: {
        //     input(val) {
        //       that.searchform.SchoolName = val
        //     },
        //   },
        // },
        {
          col: 4,
          hidden: false,
          label: "软件分类", // label文字
          prop: "AppClass", // 字段名
          element: "el-select", // 指定elementui组件
          initValue: '', // 字段初始值,
          placeholder: "请选择软件分类", // elementui组件属性
          options: [],
          rules: [], // elementui组件属性
          events: {
            input(val) {
              that.searchform.AppClass = val
            },
          },
        },
        {
          col: 6,
          label: "软件名称",
          prop: "AppName",
          element: "el-input",
          placeholder: "请输入软件名称",
          maxlength: 50,
          events: {
            input(val) {
              that.searchform.AppName = val
            },
          },
        },
        {
          col: 6,
          label: "资产选择",
          prop:"DeviceName",
          element: "el-select",
          initValue: "",
          placeholder: "请选择资产",
          options:[],
          events: {
            input(val) {
              that.searchform.DeviceName = val
            },
          },
        },
        // {
        //   col: 8,
        //   label: "描述关键字",
        //   prop: "Descp",
        //   element: "el-input",
        //   placeholder: "请输入描述关键字",
        //   maxlength: 50,
        //   events: {
        //     input(val) {
        //       that.searchform.Descp = val
        //     },
        //   },
        // },
      ],
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.pageSize = Cookies.get('DefaultPageLength') * 1
    // let endTime = new Date(new Date().setHours(0, 0, 0, 0))
    // let startTime = endTime - (Cookies.get('DefaultLogDays') * 1 * 3600 * 24 * 1000);
    // let arr = [ parseTime(startTime), '']
    // this.formOptions.map( item => {
    //   if(item.label === '日期'){
    //     item.initValue = arr
    //   }
    // })
    // this.$set(this.searchform,'timeRange', arr)
    this.$set(this.searchform,'MinPercent', 0)
    this.$set(this.searchform,'MaxPercent', 100)
    this.getData()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    // this.GetSchoolStatusSumTree()
    this.GetDictSoftwareTree()
    this.CenterGetDevice()
  },
  methods: {
    async CenterGetDevice(){
      const data = {
        Paging:{
          QueryPageNo: 1,
          QueryPageLength: 100000000
        },
        Filter:{
          Status: 0,
        }
      }
      const res = await connrequest('CenterGetDevice', data)
      let assetList = []
      res.Data.map(item => {
        assetList.push({ label: item.DeviceName, value: item.DeviceID })
      })
      this.formOptions.map( item => {
        if(item.label === '资产选择'){
          item.options = assetList
        }
      })
    },
    // 获取子节点的校区
    async lazyLoad(node, resolve){
      if(node.level < 3){
        resolve(node.data) 
      }else{
        const data = {
          Paging:{
            QueryPageNo: 1,
            QueryPageLength: 100000
          },
          Filter:{
            SecondArea: node.label,
          }
        }
        const res = await connrequest('GetSchool', data)
        let arr = []
        res.Data.map(item => {
          arr.push( {SubClass: item.SchoolName, value: item.SchoolName, level: 4, children: undefined} )
        })
        resolve(arr) 
      }
    },
    // 获取校区树
    async GetSchoolStatusSumTree() {
      const res = await connrequest('GetSchoolStatusSumTree')
      this.formOptions.map( item => {
        if(item.label === '分区校区选择'){
          item.options = [this.transformData(res.Data)]
        }
      })
    },
    transformData(inputData) {
      const { RootName, PrimArea} = inputData;
        return {
          SubClass: RootName,
          value: RootName,
          level: 1,
          children: PrimArea.map(area => ({
            SubClass: area.PrimAreaName,
            value: area.PrimAreaName,
            level: 2,
            children: area.SecondArea.map(secondArea => ({
              SubClass: secondArea.SecondAreaName,
              value: secondArea.SecondAreaName,
              level: 3,
          }))
        }))
      }
    },
    async GetDictSoftwareTree(){
      const res = await connrequest('GetDictSoftwareTree')
      let arr = [{label: '全部', value: ''}]
      res.Data.Class.map(item => {
        arr.push( {label: item.Name, value: item.Name} )
      })
      this.formOptions.map( item => {
        if(item.label === '软件分类'){
          item.options = arr
        }
      })
      this.partitionList = arr
      this.$set(this.searchform,'ProcClass', '')
    },
    changeModer(row){
      let partitionList = this.partitionList.filter(item => item.label !== '全部')
      this.dictionaryList = partitionList
      this.Moder = {...row, Property: row.Property || 3, Class: row.Class || partitionList[0]?.label}
      this.moderVisible = true;
    },
    handleChange(){},
    // 获取所有数据
    getData(){
      this.GetEventLog()
      switch (this.tabTitle) {
        case '按日统计趋势':
          this.GetEventLogSumGroupByDate()
          break;
        case '按分区统计分析':
          this.GetInstallAppSumGroupByArea()
          break;
        case '按校区统计分析':
          this.GetInstallAppSumGroupBySchool()
          break;
        case '按资产统计分析':
          this.GetInstallAppSumGroupByDevice()
          break;
        case '按软件分类统计分析':
          this.GetInstallAppSumGroupByClass()
          break;
        default:
          this.GetInstallAppSumGroupByName()
          break;
      }
    },
    echartsClick(val,title){
      this.pageNum = 1
      if(title === '按日统计趋势'){
        this.searchobj = { StartTime: `${val} 00:00:00`, EndTime: `${val} 23:59:59` }
        this.GetEventLog(this.searchobj)
      }else if(title === '按分区统计分析'){
        this.searchobj = { PrimArea: val.split('_')[0], SecondArea: val.split('_')[1] }
        this.GetEventLog(this.searchobj)
      }else if(title === '按校区统计分析'){
        this.searchobj = { SchoolName: val }
        this.GetEventLog(this.searchobj)
      }else if(title === '按资产统计分析'){
        this.searchobj = { DeviceName: val }
        this.GetEventLog(this.searchobj)
      }else if(title === '按软件分类统计分析'){
        this.searchobj = { AppClass: val === '未知分类' ? 'NULL' : val }
        this.GetEventLog(this.searchobj)
      }else{
        this.searchobj = { AppName: val }
        this.GetEventLog(this.searchobj)
      }
      // this.GetEventLog()
    },
    tabClick(row){
      this.tabTitle = row.label
      switch (row.label) {
        case '按日统计趋势':
          this.GetEventLogSumGroupByDate()
          break;
        case '按分区统计分析':
          this.GetInstallAppSumGroupByArea()
          break;
        case '按校区统计分析':
          this.GetInstallAppSumGroupBySchool()
          break;
        case '按资产统计分析':
          this.GetInstallAppSumGroupByDevice()
          break;
        case '按软件分类统计分析':
          this.GetInstallAppSumGroupByClass()
          break;
        default:
          this.GetInstallAppSumGroupByName()
          break;
      }
    },
    getnewarr(departments, employees){
      const newDepartmentArray = [];
      //遍历departments数组
      departments.forEach(department => {
        //新建一个对象，用于存储合并后的数据
        const newDepartmentObj = {
            DepartmentName: department.DepartmentName,
            SubClass: department.DepartmentName,
            ParentName: department.ParentName,
            ID: department.ID,
            ParentID: department.ParentID,
            children: []
        };
        //遍历employees数组
        employees.forEach(employee => {
          //如果employee的Department和department的DepartmentName相同
          if (employee.Department === department.DepartmentName) {
            //将该employee对象添加到newDepartmentObj的children数组中
            newDepartmentObj.children.push(employee);
          }
        });
        //将newDepartmentObj添加到newDepartmentArray数组中
        newDepartmentArray.push(newDepartmentObj);
      });
      const convertedArray = this.convertArray(newDepartmentArray);
      this.formOptions.map( item => {
        if(item.label === '终端用户'){
          item.options = convertedArray
        }
      })
    },
    convertArray(data) {
      const map = {};
      const result = [];
      data.forEach(item => {
        if(!item.children){
          item.children = [];
        }
        map[item.ID] = item;
      });
      data.forEach(item => {
        if (item.ParentID !== 0) {
          const parent = map[item.ParentID];
          parent.children.push(item);
        } else {
          result.push(item);
        }
      });
      return result;
    },
    // 获取事件日志列表
    async GetEventLog(searchobj = {}){
      const data = {
        Paging: {
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
        Filter: {
          StartTime: this.searchform.timeRange?.[0] ||  '',
          EndTime: this.searchform.timeRange?.[1] || '',
          AppClass: this.searchform.AppClass,
          AppName: this.searchform.AppName,
          Descp: this.searchform.Descp,
          DeviceID: this.searchform.DeviceName,
          InstallAppType: 3,
          ...searchobj
        }
      }
      const res = await connrequest('GetInstallApp', data)
      res.Data = res.Data || []
      res.Data = res.Data.map(item => {
        item.TransTime = parseTime(item.TransTime)
        return item
      })
      this.tableData = res.Data
      this.total = res.Paging.TotalCount
    },
    // 获取事件日期统计
    async GetEventLogSumGroupByDate(){
      let xAxis = []
      let series= []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] ||  '',
          EndTime: this.searchform.timeRange?.[1] || '',
          AppClass: this.searchform.AppClass,
          AppName: this.searchform.AppName,
          Descp: this.searchform.Descp,
          DeviceID: this.searchform.DeviceName,
          InstallAppType: 3,
        }
      }
      const res = await connrequest('GetEventLogSumGroupByDate', data)
      res.Data = res.Data || []
      res.Data.map( item =>{
        xAxis.push(item.Name)
        series.push(item.Count)
      })
      this.barchartData = {xAxis,series}
    },
    // 按分区统计分析
    async GetInstallAppSumGroupByArea(){
      let arr = []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] ||  '',
          EndTime: this.searchform.timeRange?.[1] || '',
          AppClass: this.searchform.AppClass,
          AppName: this.searchform.AppName,
          Descp: this.searchform.Descp,
          DeviceID: this.searchform.DeviceName,
          InstallAppType: 3,
        }
      }
      const res = await connrequest('GetInstallAppSumGroupByArea', data)
      res.Data = res.Data || []
      res.Data.map( item =>{
        arr.push({name: item.Name, value: item.Count})
      })
      this.pie1Data = arr
    },
    // 按校区统计分析
    async GetInstallAppSumGroupBySchool(){
      let arr = []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] ||  '',
          EndTime: this.searchform.timeRange?.[1] || '',
          AppClass: this.searchform.AppClass,
          AppName: this.searchform.AppName,
          Descp: this.searchform.Descp,
          DeviceID: this.searchform.DeviceName,
          InstallAppType: 3,
        }
      }
      const res = await connrequest('GetInstallAppSumGroupBySchool', data)
      res.Data = res.Data || []
      res.Data.map( item =>{
        arr.push({name: item.Name, value: item.Count})
      })
      this.pie2Data = arr
    },
    // 按事件资产统计分析
    async GetInstallAppSumGroupByDevice(){
      let arr = []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] ||  '',
          EndTime: this.searchform.timeRange?.[1] || '',
          AppClass: this.searchform.AppClass,
          AppName: this.searchform.AppName,
          Descp: this.searchform.Descp,
          DeviceID: this.searchform.DeviceName,
          InstallAppType: 3,
        }
      }
      const res = await connrequest('GetInstallAppSumGroupByDevice', data)
      res.Data = res.Data || []
      res.Data.map( item =>{
        arr.push({name: item.Name, value: item.Count})
      })
      this.pie3Data = arr
    },
    // 按软件分类统计分析
    async GetInstallAppSumGroupByClass(){
      let arr = []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] ||  '',
          EndTime: this.searchform.timeRange?.[1] || '',
          AppClass: this.searchform.AppClass,
          AppName: this.searchform.AppName,
          Descp: this.searchform.Descp,
          DeviceID: this.searchform.DeviceName,
          InstallAppType: 3,
        }
      }
      const res = await connrequest('GetInstallAppSumGroupByClass', data)
      res.Data = res.Data || []
      res.Data.map( item =>{
        arr.push({name: item.Name ? item.Name : '未知分类', value: item.Count})
      })
      this.pie4Data = arr
    },
    // 按软件名称统计分析
    async GetInstallAppSumGroupByName(){
      let arr = []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] ||  '',
          EndTime: this.searchform.timeRange?.[1] || '',
          AppClass: this.searchform.AppClass,
          AppName: this.searchform.AppName,
          Descp: this.searchform.Descp,
          DeviceID: this.searchform.DeviceName,
          InstallAppType: 3,
        }
      }
      const res = await connrequest('GetInstallAppSumGroupByName', data)
      res.Data = res.Data || []
      res.Data.map( item =>{
        arr.push({name: item.Name, value: item.Count})
      })
      this.pie5Data = arr
    },
    async submit(){
      const data = {
        Data: {
          Action: 1,
          Detail: {
            Descp: this.Moder.AppName,
            Factory: this.Moder.Descp,
            Class: this.Moder.Class,
            Version: this.Moder.Version,
            OSClass: this.Moder.OSClass,
            OSType: this.Moder.OSType,
            Property: this.Moder.Property,
          }
        }
      }
      const res = await connrequest('EditDictInstallApp', data)
      if(res.Status.StatusCode === 0){
        this.$message.success('加入字典成功')
        this.moderVisible = false
        this.getData()
      }
    },
    // 搜索
    search(val) {
      this.pageNum = 1
      this.searchobj = {}
      this.searchform = {...val}
      if(this.searchform.timeRange){
        this.searchobj = { StartTime: this.searchform?.timeRange[0] || '', EndTime: this.searchform?.timeRange[1] || '' }
      }
      this.getData()
    },
    // 重置
    reset(){
      let xTime = new Date().getTime()
      let endTime = new Date(new Date().setHours(0, 0, 0, 0))
      let startTime = endTime - (Cookies.get('DefaultLogDays') * 1 * 3600 * 24 * 1000);
      // let arr = [ parseTime(startTime), parseTime(xTime)]
      let arr = [ parseTime(startTime), '']
      this.pageNum = 1
      this.formOptions = this.formOptions.map( item => {
        if(item.label === "日期"){
          item.initValue = arr
        }else if(item.label === "统计排名"){
          item.initValue = 10
        }else{
          item.initValue = ""
        }
        return item
      })
      this.searchform = {}
      this.$set(this.searchform,'timeRange', arr)
      this.$set(this.searchform,'MinPercent', 0)
      this.$set(this.searchform,'MaxPercent', 100)
      this.$refs.connsearch.addInitValue()
      this.getData()
    },
    handleSizeChange(pageSize){
      this.pageSize = pageSize
      this.pageNum = 1
      this.GetEventLog({...this.searchobj, StartTime: this.searchobj?.StartTime || this.searchform.timeRange?.[0] ||  '', EndTime: this.searchobj?.EndTime || this.searchform.timeRange?.[1] ||  ''})
    },
    handleCurrentChange( pageNum ){
      this.pageNum = pageNum
      this.GetEventLog({...this.searchobj, StartTime: this.searchobj?.StartTime || this.searchform.timeRange?.[0] ||  '', EndTime: this.searchobj?.EndTime || this.searchform.timeRange?.[1] ||  ''})
    },
    handleClick() {
      this.tab = !this.tab
    },
  },
};
</script>
<style lang="scss" scoped>
@import "./components/css/conncss.scss";
</style>